const Movie = require("../models/movie");
const redisClient = require('../config/redis');

// 通用缓存清理函数
async function deleteMovieRelatedCache() {
  try {
    // 直接删除已知的固定键
    await redisClient.del('allMovies');
    // 需要清理的键模式列表
    const patterns = [
      'movie:*',       // 单个电影缓存
      'search:*',      // 搜索相关缓存
      'rating:*',      // 评分排序缓存
      'reviewsCount:*' // 评论数排序缓存
    ];
    // 使用 Promise.all 并行处理所有模式
    await Promise.all(patterns.map(async (pattern) => {
      let cursor = '0';
      do {
        // 使用 SCAN 命令迭代匹配键
        const reply = await redisClient.scan(cursor, { MATCH: pattern });
        cursor = reply.cursor;
        
        if (reply.keys.length > 0) {
          // 批量删除匹配的键
          await redisClient.del(reply.keys);
        }
      } while (cursor !== '0');
    }));
  } catch (err) {
    console.error('缓存清理失败:', err);
  }
}

exports.getAllMovies = async (req, res) => {
  try {
    // 从 Redis 获取缓存数据
    const cachedData = await redisClient.get('allMovies');
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }
    const movies = await Movie.findAll();
    // 将数据存入 Redis 缓存
    await redisClient.setEx('allMovies', 60, JSON.stringify(movies)); // 缓存 60 秒
    res.json(movies);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.getMovieById = async (req, res) => {
  try {
    const { id } = req.params;
    // 从 Redis 获取缓存数据
    const cachedData = await redisClient.get(`movie:${id}`);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }
    const movie = await Movie.findById(id);
    if (!movie) {
      return res.status(404).json({ error: "电影不存在" });
    }
    // 将数据存入 Redis 缓存
    await redisClient.setEx(`movie:${id}`, 60, JSON.stringify(movie)); // 缓存 60 秒
    res.json(movie);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.searchMovies = async (req, res) => {
  try {
    const { title, tag, startYear, endYear, page = 1, limit = 5 } = req.body;
    const offset = (parseInt(page) - 1) * parseInt(limit);
    // 创建缓存键
    const cacheKey = `search:${title}:${tag}:${startYear}:${endYear}:${page}:${limit}`;
    // 从 Redis 获取缓存数据
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }
    const searchParams = { title, tag, startYear, endYear };
    const movies = await Movie.search(searchParams, offset, parseInt(limit));
    // 将数据存入 Redis 缓存
    await redisClient.setEx(cacheKey, 60, JSON.stringify(movies)); // 缓存 60 秒
    res.json(movies);
  } catch (error) {
    res.status(500).json({ error: '内部服务错误' });
  }
};

exports.getMoviesByRating = async (req, res) => {
  try {
    const { page = 1, limit = 5 } = req.body;
    const offset = (parseInt(page) - 1) * parseInt(limit);
    // 创建缓存键
    const cacheKey = `rating:${page}:${limit}`;
    // 从 Redis 获取缓存数据
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }
    const movies = await Movie.searchByRating(offset, parseInt(limit));
    // 将数据存入 Redis 缓存
    await redisClient.setEx(cacheKey, 60, JSON.stringify(movies)); // 缓存 60 秒
    res.json(movies);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.getMoviesByReviewsCount = async (req, res) => {
  try {
    const { page = 1, limit = 5 } = req.body;
    const offset = (parseInt(page) - 1) * parseInt(limit);
    // 创建缓存键
    const cacheKey = `reviewsCount:${page}:${limit}`;
    // 从 Redis 获取缓存数据
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }
    const movies = await Movie.searchByReviewsCount(offset, parseInt(limit));
    // 将数据存入 Redis 缓存
    await redisClient.setEx(cacheKey, 60, JSON.stringify(movies)); // 缓存 60 秒
    res.json(movies);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.addMovie = async (req, res) => {
  try {
    const { title, description, poster_url, rating, release_year, tags } = req.body;
    const movieId = await Movie.create({
      title,
      description,
      rating,
      poster_url,
      release_year,
      tags,
    });
    // 清除相关缓存
    await deleteMovieRelatedCache();
    res.status(201).json({ message: '电影添加成功', movieId });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '内部服务错误' });
  }
};

exports.updateMovie = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description, poster_url, rating, release_year, tags } = req.body;
    await Movie.update(id, {
      title,
      description,
      rating,
      poster_url,
      release_year,
      tags,
    });
    // 清除相关缓存
    await deleteMovieRelatedCache();
    res.json({ message: '电影更新成功' });
  } catch (error) {
    res.status(500).json({ error: '内部服务错误' });
  }
};

exports.deleteMovie = async (req, res) => {
  try {
    const { id } = req.params;
    await Movie.delete(id);
    // 清除相关缓存
    await deleteMovieRelatedCache();
    res.json({ message: "电影及对应评论和标签关系删除成功" });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};